
/* Konstruktors */
var Castle = function() {
    this.mapStorage = Array();
    this.objectStorage = Array();
    
    this.wallwidth = 25;
    this.wallheight = 24;    
};

Castle.prototype.loadFile = function(num) {
    this.currentMap = num;
    
    $.ajax({
        url: "../loadmap.php?map="+num,
        dataType: 'json'
    }).done(function(req) { 
        castle.mapStorage = req;
        castle.drawCastle();
    });
};

/* F-tion to draw castle */
Castle.prototype.drawCastle = function() {
    if (typeof(this.mapStorage[0]) == 'object') {
        var castle_element = '';
        var wallobject = '';
        
        // set eagle position
        this.mapStorage[24][12] = 'Z';
        this.mapStorage[24][13] = 'Z';
        this.mapStorage[25][12] = 'Z';
        this.mapStorage[25][13] = 'Z';

        // my tank
        /*this.mapStorage[24][9] = 'A';
        this.mapStorage[24][10] = 'A';
        this.mapStorage[25][9] = 'A';
        this.mapStorage[25][10] = 'A';
*/
        for (y=1;y<=26;y++) {
            this.objectStorage[y] = new Array();
            for (x=1;x<=27;x++) {
                wallobject = 0;
                castle_element = this.mapStorage[y-1][x-1];
                if (castle_element != ".") {
                    wallobject = new Wallobject(castle_element, x, y);
                    wallobject.draw();
                }
                
                // store this object into storage
                this.objectStorage[y][x] = wallobject;
            }
        }
        
        // create eagle object
        wallobject = new Wallobject('eagle', 13, 25);
        wallobject.draw();
        
        // put tank on screen
        
        desk.tank.draw();
        this.objectStorage[24][9] = desk.tank;
    }
};

/* Clear map */
Castle.prototype.resetCurrentMap = function() {
    var wallobject = '';
    
    if (typeof(this.objectStorage[1]) == 'object') {
        for (y=1;y<=26;y++) {
            for (x=1;x<=27;x++) {
                wallobject = this.objectStorage[y][x];
                if (typeof(wallobject) == 'object') {
                    wallobject.freeObject();

                    // remove from object storage
                    delete this.objectStorage[y][x];
                }
            }
        }
    }
};

/* Wall object */
var Wallobject = function(type, x, y) {  
    this.type = type;
    this.x = x;
    this.y = y;
};

/* Remove stored element from document */
Wallobject.prototype.freeObject = function() {
    this.htmlObject.remove();
};

Wallobject.prototype.draw = function() {
    var spritetype = "";
    
    switch (this.type) {
        case '#': // brick
            spritetype = "brick1";
            break;
        case '@': // rock
            spritetype = "rock";
            break;
        case '%': // grass
            spritetype = "grass";
            break;
        case '~': // water
            spritetype = "water1";
            break;
        case '-': // sand - froze
            spritetype = "sand";
            break;
        case 'eagle':
            spritetype = "eagle";
            break;
    }
    
    var left = this.x * desk.castle.wallwidth - desk.castle.wallwidth;
    var top = this.y * desk.castle.wallheight - desk.castle.wallheight;
    
    var $newdiv1 = $('<div class="'+spritetype+'"></div>');
    $newdiv1.css('left', left);
    $newdiv1.css('top', top);
    $('#castle').append( $newdiv1 );
    
    // store html object that we can later unset this object
    this.htmlObject = $newdiv1;
};


/* Globaalaas f-jas */

var Desk = function() {
};

/* F-ja, ko izsauc no aarpuses lai saaktu speeli */
Desk.prototype.load = function() {
	this.init();
	//this.timer.start();
  //this.timer2.startTimer();
}
var cnt = 20;

Desk.prototype.loadmap = function() {
    castle.resetCurrentMap();
    
    castle.loadFile(cnt);
    this.castle = castle;
    cnt ++;
}

Desk.prototype.init = function() {
    this.timer = new Timer();
    this.timer.setInterval(900);
    var game = new Game();
    this.timer.process = function() {
        game.process('#castle');
        game.process2('#castle');
    }
    
    // create my tank
    this.tank = new Tank(9, 25);
    
    this.loadmap();
    
    /*
    this.timer2 = new Timer();
    this.timer2.setInterval(200);
    this.timer2.process = function() {
        game.process('#castle2');
        game.process2('#castle2');
    }*/
};

Desk.prototype.stop = function() {
    this.timer.stop();
}

Desk.prototype.pause = function() {
    this.timer.pause();
}

Desk.prototype.play = function() {
    this.timer.play();
}

/* Game object */

var Game = function() {
};

Game.prototype.process = function(target) {
    $(target).append('.');
};

Game.prototype.process2 = function(target) {
    $(target).append('#');
};

/* Taimera objekts */

var Timer = function() {
    this.obj = 0;
    this.interval = 1000; // default 1 second
};

Timer.prototype.setInterval = function(i) {
    this.interval = i;
}

Timer.prototype.start = function() {        
    if (!this.obj) {
        this.obj = $.timer(
            this.process,
            this.interval,
            true
            );	
    }
}

/* F-tion to stop timer */
Timer.prototype.stop = function() {
	if (this.obj) {
		this.obj.stop();
	}
}

/* F-tion to pause timer */
Timer.prototype.pause = function() {
	if (this.obj) {
		this.obj.pause();
	}
}

/* F-tion to resume timer */
Timer.prototype.play = function() {
	if (this.obj) {
		this.obj.play();
	}
}

/* Tank object */
var Tank = function(x, y) {  
    this.direction = 1; // default direction up
    
    this.x = x;
    this.y = y;
    
    this.step = 5;
    
    this.tankwidth = 39;
};

Tank.prototype.setPosition = function(x,y) {
    this.x = x;
    this.y = y;
    
    this.htmlObject = 0;
};

/* draw tank */
Tank.prototype.draw = function() {
    var spritetype = "";
    switch (this.direction) {
        case 1: // up
            spritetype = 'minetank1up';
            break;
        case 2: // right
            spritetype = 'minetank1right';
            break;
        case 3: // down
            spritetype = 'minetank1down';
            break;
        case 4: // left
            spritetype = 'minetank1left';
            break;
    }
    
    // create new object
    if (!this.htmlObject) {
        var left = this.x * desk.castle.wallwidth - desk.castle.wallwidth;
        var top = this.y * desk.castle.wallheight - desk.castle.wallheight;

        var $newdiv1 = $('<div class="'+spritetype+'"></div>');
        $newdiv1.css('left', left);
        $newdiv1.css('top', top);
        $('#castle').append( $newdiv1 );

        // store html object that we can later unset this object
        this.htmlObject = $newdiv1;

        this.left = left;
        this.top = top;
    } else {
        // change existing object
        this.htmlObject.css('left', this.left);
        this.htmlObject.css('top', this.top);
        this.htmlObject.attr('class', spritetype);
    }
};

Tank.prototype.keyaction = function() {
    if (desk.pressedKey) {
        $('#info1').html( desk.pressedKey );    

        var tmpX = Math.floor( this.left / desk.castle.wallwidth );
        var tmpY = Math.floor( this.top / desk.castle.wallheight );
  
        var tmpX1 = 0;
        var tmpY1 = 0;
  
        switch (desk.pressedKey) {
        case 37: //left
            this.direction = 4;
            tmpX = Math.floor( (this.left - this.step) / desk.castle.wallwidth );
            tmpY1 = Math.floor( (this.top + this.tankwidth) / desk.castle.wallheight );
            
            if ((desk.castle.mapStorage[ tmpY ][ tmpX ] == '.' && 
                desk.castle.mapStorage[ tmpY1 ][ tmpX ] == '.') || 
               (desk.castle.mapStorage[ tmpY ][ tmpX ] == '%' && 
                desk.castle.mapStorage[ tmpY1 ][ tmpX ] == '%')) {
                this.left -= this.step;
            }
        break;
        case 39: // right
            this.direction = 2;
            tmpX = Math.floor( (this.left + this.tankwidth + this.step) / desk.castle.wallwidth );
            tmpY1 = Math.floor( (this.top + this.tankwidth) / desk.castle.wallheight );
            
            if ((desk.castle.mapStorage[ tmpY ][ tmpX ] == '.' && 
                desk.castle.mapStorage[ tmpY1 ][ tmpX ] == '.') || 
               (desk.castle.mapStorage[ tmpY ][ tmpX ] == '%' && 
                desk.castle.mapStorage[ tmpY1 ][ tmpX ] == '%')) {
                this.left += this.step;
            }
        break;
        case 40: // down
            this.direction = 3;
            tmpY = Math.floor( (this.top + this.tankwidth + this.step) / desk.castle.wallheight );
            tmpX1 = Math.floor( (this.left + this.tankwidth) / desk.castle.wallwidth );
            
            if ((desk.castle.mapStorage[ tmpY ][ tmpX ] == '.' && 
                desk.castle.mapStorage[ tmpY ][ tmpX1 ] == '.') || 
                (desk.castle.mapStorage[ tmpY ][ tmpX ] == '%' && 
                desk.castle.mapStorage[ tmpY ][ tmpX1 ] == '%')) {
                this.top += this.step;
            }
        break;
        case 38: // up
            this.direction = 1;
            tmpY = Math.floor( (this.top - this.step) / desk.castle.wallheight );
            tmpX1 = Math.floor( (this.left + this.tankwidth) / desk.castle.wallwidth );
            
            if ((desk.castle.mapStorage[ tmpY ][ tmpX ] == '.' && 
                desk.castle.mapStorage[ tmpY ][ tmpX1 ] == '.') || 
                (desk.castle.mapStorage[ tmpY ][ tmpX ] == '%' && 
                desk.castle.mapStorage[ tmpY ][ tmpX1 ] == '%')) {
                this.top -= this.step;
            }
            break;
        
        }

        this.x = tmpX;
        this.y = tmpY;
        switch (desk.pressedKey) {
            case 32: // space
                var bullet = new Bullet(this.left, this.top, this.direction, this.tankwidth);
                bullet.draw();

                break;
        }

        $('#info2').html( "X:"+this.x+", Y:"+ this.y );
        $('#info3').html( "Y: "+this.top+" : "+ tmpY );
        $('#info4').html( "X1:"+(this.left + this.tankwidth)+" : "+tmpX1  );
        $('#info5').html( "Y1:"+(this.top + this.tankwidth)+" : "+tmpY1  );
        $('#info6').html( desk.castle.mapStorage[ tmpY ][ tmpX ]+" "+desk.castle.mapStorage[ tmpY ][ tmpX1 ] );
    
        this.draw();
  
		// arii peec kustiibaam jaapiefiksee ieprieksheejaa poziicija
		//this.prevElemXPos = this.elemXPos;
		//this.prevElemYPos = this.elemYPos;
		//this.pressedKey = 0;
    
	}
};

/* Bullet object */

var Bullet = function(left, top, direcion, tankwidth) {
    this.left = left;
    this.top = top;
    this.tankwidth = tankwidth;
    
    this.direction = direcion;
};

Bullet.prototype.draw = function() {
    // create new object
    if (!this.htmlObject && this.direction) {
        var left;
        var top;

        var spritetype = "";
        switch (this.direction) {
            case 1: // up
                spritetype = 'bulletup';
                left = this.left + this.tankwidth / 2;
                top = this.top - 12;
                this.tankwidth
                break;
            case 2: // right
                spritetype = 'bulletright';
                left = this.left + this.tankwidth + 4
                top = this.top + this.tankwidth / 2;
                
                break;
            case 3: // down
                spritetype = 'bulletdown';
                left = this.left + this.tankwidth / 2;
                top = this.top + this.tankwidth + 4
                
                break;
            case 4: // left
                spritetype = 'bulletleft';
                left = this.left - 12;
                top = this.top + this.tankwidth / 2;
                
                break;
        }

        var $newdiv1 = $('<div class="'+spritetype+'"></div>');
        $newdiv1.css('left', left);
        $newdiv1.css('top', top);
        $('#castle').append( $newdiv1 );

        // store html object that we can later unset this object
        this.htmlObject = $newdiv1;
        this.currentClass = spritetype
        this.left = left;
        this.top = top;
        
        //this.startFlying();
    } else {
        // change existing object
        this.htmlObject.css('left', this.left);
        this.htmlObject.css('top', this.top);
    }
};

/* Function to do bullet flying */
Bullet.prototype.startFlying = function() {
    var timer = new Timer();
    timer.setInterval(100);
    
    timer.process = function() {
        // Te es paliku!
    }
};


/* F-ja, kas vareetu arii nebuut klasee, bet publiska - taa reagjee uz katru piespiesto taustinju un nodod kocinju taalaak */
function keypress(ev) {
	if (ev) {
		var key = ev.keyCode;
	} else {
		var key = window.event.keyCode;
	}
	
	// piefikseejam piespiesto pogu
	desk.pressedKey = key;
  desk.tank.keyaction();
}

var desk = new Desk(); 
var castle = new Castle();

document.onkeydown = keypress;